import { useEffect, useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
} from "react-native";
import { getStorageData, setStorageData } from "utils";
import BouncyCheckboxGroup, {
  type ICheckboxButton,
} from "react-native-bouncy-checkbox-group";
import toast from "utils/toast";
import translate from "utils/translate";
type FormData = {
  goodsName?: string;
  price?: string;
  unit?: string;
  id?: string;
  goodsCode?: string;
  weight?: string;
  limit?: string;
  discount_lv?: string;
  remark?: string;
  changePrice?: string;
  mode?: string;
  discount?: string;
};
type FormKeys = keyof FormData;
export default ({
  navigation,
  route: { params },
}: RootStackScreenProps<"addGoods">) => {
  const [form, setForm] = useState<FormData>({
    goodsName: "",
    price: "",
    unit: translate("main.weightUnit"),
    goodsCode: "0",
    remark: "0",
    discount_lv: "0",
    limit: "0",
    weight: "0",
    changePrice: "10",
    mode: "10",
    discount: "10",
  });
  useEffect(() => {
    const { index, createTime, id, ...rest } = params;
    setForm((data) => {
      return {
        ...data,
        ...rest,
        id: index?.toString(),
      };
    });
  }, []);
  const handleSave = async () => {
    for (let p of List) {
      if (
        p.maxLength &&
        (form[p.prop as FormKeys]?.replaceAll(/[\u4e00-\u9fa5]/g, "aa")
          ?.length ?? 0) > (p.maxLength ?? 0)
      ) {
        return toast(translate("main.tooLong"));
      }
    }
    if (form.price && form.goodsName) {
      // if (form.goodsName.replaceAll(/[\u4e00-\u9fa5]/g, "aa").length > 10) {
      //   return toast("输入的商品名称过长");
      // }
      const StorageData = await getStorageData("classList");
      const classList = StorageData ? JSON.parse(StorageData) : [];
      const index = classList.findIndex((item: { id: number }) => {
        return item.id === params.id;
      });

      if (params.index) {
        const { goodsList, ...rest } = classList[index];
        goodsList.splice(params.index - 1, 1, form);
        classList.splice(index, 1, {
          ...rest,
          goodsList,
        });
      } else {
        const { goodsList = [], ...rest } = classList[index];
        goodsList.push(form);
        classList.splice(index, 1, {
          ...rest,
          goodsList,
        });
      }
      setStorageData("classList", JSON.stringify(classList)).then(() => {
        navigation.goBack();
      });
    } else {
      toast(translate("main.tooLong"));
    }
  };
  const handleChange = (value: string, key: FormKeys) => {
    setForm((prevForm) => ({
      ...prevForm,
      [key]: value,
    }));
  };
  const List = [
    {
      label: translate("main.id"),
      prop: "id",
    },
    {
      label: translate("class.goodsName"),
      prop: "goodsName",
      placeholder: translate("class.tipGoodsName"),
      maxLength: 12,
    },
    {
      label: translate("main.code"),
      prop: "goodsCode",
      placeholder: "0~99999",
      defaultValue: form.goodsCode,
      maxLength: 13,
    },
    {
      label: translate("class.price"),

      prop: "price",
      placeholder: translate("class.priceTip"),
      maxLength: 6,
    },
    {
      label: translate("main.Change"),
      prop: "changePrice",
      component: BouncyCheckboxGroup,
      props: {
        data: [
          {
            id: "10",
            text: translate("main.VariableValency"),
            fillColor: "#0081ff",
            textStyle: {
              textDecorationLine: "none",
            },
          },
          {
            id: "11",
            fillColor: "#0081ff",
            text: translate("main.ImmutableValence"),

            style: {
              marginLeft: 30,
            },
            textStyle: {
              textDecorationLine: "none",
            },
          },
        ],
        initial: form.changePrice,
      },
    },
    {
      label: translate("main.SalesModel"),
      prop: "mode",
      component: BouncyCheckboxGroup,
      props: {
        data: [
          {
            id: "10",
            text: translate("main.weight"),
            fillColor: "#0081ff",
            textStyle: {
              textDecorationLine: "none",
            },
          },
          {
            id: "11",
            text: translate("main.quantity"),
            fillColor: "#0081ff",
            style: {
              marginLeft: 30,
            },
            textStyle: {
              textDecorationLine: "none",
            },
          },
        ],
        initial: form.mode,
      },
    },
    {
      label: translate("class.peelWeight"),
      prop: "weight",
      placeholder: translate("toCmplete"),
      defaultValue: form.weight,
      maxLength: 5,
    },
    {
      label: translate("main.ShelfLife"),
      prop: "limit",
      placeholder: "translate('toCmplete')",
      defaultValue: form.limit,
      maxLength: 4,
    },
    {
      label: translate("main.OfferDiscount"),
      prop: "discount",
      component: BouncyCheckboxGroup,
      props: {
        data: [
          {
            id: "10",
            text: translate('main.NoDiscount'),
            fillColor: "#0081ff",
            textStyle: {
              textDecorationLine: "none",
            },
          },
          {
            id: "11",
            text: translate('main.Discount'),
            fillColor: "#0081ff",
            style: {
              marginLeft: 30,
            },
            textStyle: {
              textDecorationLine: "none",
            },
          },
        ],
        initial: form.discount,
      },
    },
    {
      label: translate('main.DiscountRate'),
      prop: "discount_lv",
      placeholder: translate("toCmplete"),
      defaultValue: form.discount_lv,
      maxLength: 2,
    },
    {
      label: translate("manage.remark"),
      prop: "remark",
      placeholder: translate("main.remarkTip"),
      defaultValue: form.remark,
      maxLength: 2,
    },
    {
      label: translate("class.unit"),
      prop: "unit",
      placeholder: translate("class.unitTip"),
      defaultValue: form.unit,
      maxLength: 4,
    },
  ];
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: "#fff",
      }}
    >
      <ScrollView
        style={{
          flex: 1,
          marginTop: 40,
        }}
        contentContainerStyle={{
          alignItems: "center",
        }}
      >
        {List.map((item) => {
          return (
            <View
              key={item.label}
              style={{
                flexDirection: "row",
                alignItems: "center",
                marginBottom: 20,
                width: "90%",
              }}
            >
              <Text
                style={{
                  width: 60,
                }}
              >
                {item.label}
              </Text>
              {item.component ? (
                <item.component
                  // @ts-ignore
                  data={item.props.data}
                  style={{
                    marginLeft: 10,
                  }}
                  // @ts-ignore
                  initial={item.props.initial}
                  onChange={(selectedItem: ICheckboxButton) => {
                    setForm((prevForm) => {
                      return {
                        ...prevForm,
                        [item.prop]: selectedItem.id as string,
                      };
                    });
                  }}
                ></item.component>
              ) : (
                <View
                  style={{
                    flexDirection: "row",
                    alignItems: "center",
                    borderWidth: 1,
                    borderRadius: 8,
                    marginLeft: 10,
                    marginRight: 10,
                    borderColor: "#ccc",
                    padding: 8,
                    flex: 1,
                    width: 200,
                    justifyContent: "space-between",
                  }}
                >
                  <TextInput
                    onChangeText={(value) => {
                      handleChange(value, item.prop as FormKeys);
                    }}
                    defaultValue={form[item.prop as FormKeys]}
                    style={{
                      flex: 5,
                    }}
                    //@ts-ignore
                    keyboardType={item.keyboardType}
                    multiline={item.multiline}
                    numberOfLines={item.numberOfLines}
                    placeholder={item.placeholder}
                  ></TextInput>
                  {item.prop !== "id" && (
                    <Text style={{ flex: 1, minWidth: 10, marginLeft: 5 }}>
                      {form[item.prop as FormKeys]?.replaceAll(
                        /[\u4e00-\u9fa5]/g,
                        "aa"
                      )?.length ?? 0}
                      /{item.maxLength}
                    </Text>
                  )}
                </View>
              )}
            </View>
          );
        })}
        <TouchableOpacity style={styles.button} onPress={handleSave}>
          <Text
            style={{
              textAlign: "center",
              color: "#fff",
            }}
          >
            {translate("main.save")}
          </Text>
        </TouchableOpacity>
        {params.index && (
          <TouchableOpacity
            style={{
              ...styles.button,
              backgroundColor: "#e54d42",
            }}
            onPress={async () => {
              const StorageData = await getStorageData("classList");
              const classList = StorageData ? JSON.parse(StorageData) : [];
              const index = classList.findIndex((item: { id: number }) => {
                return item.id === params.id;
              });
              const { goodsList, ...rest } = classList[index];
              goodsList.splice((params?.index ?? 0) - 1, 1);
              classList.splice(index, 1, {
                ...rest,
                goodsList,
              });
              setStorageData("classList", JSON.stringify(classList)).then(
                () => {
                  navigation.goBack();
                }
              );
            }}
          >
            <Text
              style={{
                textAlign: "center",
                color: "#fff",
              }}
            >
              {translate("main.delete")}
            </Text>
          </TouchableOpacity>
        )}
      </ScrollView>
    </View>
  );
};
const styles = StyleSheet.create({
  button: {
    backgroundColor: "#0A59F7",
    width: "60%",
    height: 50,
    marginBottom: 30,
    borderRadius: 16,
    alignItems: "center",
    justifyContent: "center",
    alignSelf: "center",
  },
});
